import os
from services.storage_service import StorageService
import io
from config import LOCAL_STORAGE_PATH

class LocalStorageService(StorageService):
    def __init__(self, base_dir="uploads"):
        self.base_dir = LOCAL_STORAGE_PATH
        os.makedirs(self.base_dir, exist_ok=True)

    def upload_file(self, path: str, file_obj: io.BytesIO, length: int):
        full_path = os.path.join(self.base_dir, path)
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        with open(full_path, "wb") as f:
            f.write(file_obj.read())

    def download_file(self, path: str) -> bytes:
        full_path = os.path.join(self.base_dir, path)
        with open(full_path, "rb") as f:
            return f.read()

    def delete_file(self, path: str):
        full_path = os.path.join(self.base_dir, path)
        if os.path.exists(full_path):
            os.remove(full_path)
            dir_path = os.path.dirname(full_path)
            if os.path.isdir(dir_path) and not os.listdir(dir_path):
                os.rmdir(dir_path)